package com.example.teach.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.teach.entity.Schedule;
import com.example.teach.entity.User;
import com.example.teach.mapper.ClassMapper;
import com.example.teach.service.ClassService;
import com.example.teach.service.ScheduleService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.teach.entity.Clazz;
import org.springframework.transaction.annotation.Transactional;


@Service
public class ClassServiceImpl extends ServiceImpl<ClassMapper, Clazz> implements ClassService {

    @Resource
    private ClassMapper classMapper;

    @Autowired
    private ScheduleService scheduleService;

    @Override
    public void create(Integer teacherId, String className,Integer majorId,Integer courseId, Integer number) {
        classMapper.create(teacherId,className,majorId,courseId,number);
    }

    @Override
    public Clazz selectByClassName(String className) {
        return classMapper.selectByClassName(className);
    }

    @Override
    public User selectByUserId(Integer userId, Integer classId) {
        return classMapper.selectByUserId(userId,classId);
    }

    @Override
    public int selectClassNumber(Integer classId) {
        return classMapper.selectClassNumber(classId);
    }

    @Override
    public void join(Integer userId, Integer classId) {
        if(classMapper.join(userId,classId)){
            classMapper.subtractOne(classId);
        }
    }

    @Override
    public void quit(Integer userId, Integer classId) {
        if(classMapper.quit(userId,classId)){
            classMapper.addOne(classId);
        }
    }

    @Override
    public void setCourseId(Integer classId,Integer courseId) {
        classMapper.updateCourseId(classId,courseId);
    }

    @Override
    public void deleteById(Integer classId) {
        classMapper.remove(classId);
    }

    @Override
    @Transactional
    public void deleteClassAndSchedule(Integer classId) {
        classMapper.remove(classId);
        if(scheduleService.exists(new QueryWrapper<Schedule>().eq("class_id", classId))){
            scheduleService.deleteById(classId);
        }
    }


}
